from django.utils import timezone
from rest_framework import serializers
from users.models import User

class AdminAuthSerializer(serializers.ModelSerializer):
    """管理员登录序列化器类"""
    token = serializers.CharField(label='jwt token',read_only=True)
    username = serializers.CharField(label='用户名')
    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'token')

        extra_kwargs = {
            'password':{
                'write_only':True
            }
        }

    # 补充校验
    # attrs是字典,=views/users.py 中登录接收的data
    def validate(self, attrs):
        """用户名,密码是否正确"""
        # 1.获取username和password
        username = attrs.get('username')
        password = attrs.get('password')
        # 2.根据username查询用户是否存在
        try:
            # is_staff标记是否是管理员
            user = User.objects.get(username=username,is_staff=True)
        except User.DoesNotExist:
            raise serializers.ValidationError('用户名错误')
        # 3.校验密码是否正确
        if not user.check_password(password):
            # 密码错误
            raise serializers.ValidationError('密码错误')
        # 将user 加到attrs中
        attrs['user'] = user
        return attrs

    #重写create,实现登录
    def create(self, validated_data):
        # 获取user对象
        user = validated_data.get('user')
        # 设置用户登录时间
        user.last_login = timezone.now()
        # 模型对象.save()
        user.save()

        # 服务器生成jwt token,(在jwt token中保存用户信息)
        from rest_framework_jwt.settings import api_settings

        # 组织payload数据的方法
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        # 生成jwt token数据的方法
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        # 组织payload数据
        payload = jwt_payload_handler(user)
        # 生成jwt token
        token = jwt_encode_handler(payload)

        # 给user对象增加一个token属性,保存jwt token用户数据
        user.token = token
        # 返回user => 客户端
        return user

class UserInfoSerializer(serializers.ModelSerializer):
    """用户序列化器类"""
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email')